package com.ruoyi.common.utils;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;

public class MenuExcelUtil {
    public static void main(String[] args) throws Exception {
        String excelFilePath = "C:\\Users\\xinhuiRong\\Desktop\\食谱详情3.xlsx"; // Change this path to your file location
        String outputBasePath = "E:\\menu3\\"; // Base output directory


        // 创建输出目录
        File outputDir = new File(outputBasePath);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        try (FileInputStream fis = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            Map<String, List<RowData>> fileContentMap = new HashMap<>();

            // 读取数据
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过标题行

                Cell firstCell = row.getCell(0); // 第一列
                Cell secondCell = row.getCell(1); // 第二列
                Cell thirdCell = row.getCell(2); // 第三列
                // 跳过空行
                if (firstCell == null || secondCell == null || thirdCell == null ||
                        firstCell.toString().trim().isEmpty() || secondCell.toString().trim().isEmpty()) {
                    continue;
                }

                // 清理文件名中的换行和回车符
                String fileName = firstCell.toString().trim().replaceAll("\r|\n", " ");
                String content = secondCell.toString().trim();
                String imageUrl = thirdCell.toString().trim();

                if (firstCell != null && secondCell != null && thirdCell != null) {
                     fileName = sanitizeFileName(firstCell.toString().trim());
                     content = secondCell.toString().trim();
                     imageUrl = thirdCell.toString().trim();

                    fileContentMap.putIfAbsent(fileName, new ArrayList<>());
                    fileContentMap.get(fileName).add(new RowData(content, imageUrl));
                }
            }

            // 输出文件和下载图片
            for (Map.Entry<String, List<RowData>> entry : fileContentMap.entrySet()) {


                String fileName =entry.getKey();
                List<RowData> rowDataList = entry.getValue();
                String folderPath = outputBasePath + fileName + "/";

                // 创建文件夹
                File folder = new File(folderPath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }

                // 写入文本文件
                File outputFile = new File(folderPath + fileName + ".txt");
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
                    int index = 1;
                    for (RowData rowData : rowDataList) {
                        writer.write(index + ". " + rowData.getContent());
                        writer.newLine();

                        // 下载图片
                        if (!rowData.getImageUrl().isEmpty()) {
                            downloadImage(rowData.getImageUrl(), folderPath +fileName+"_"+ index + ".jpg");
                        }

                        index++;
                    }
                }

                System.out.println("已生成文件夹: " + folderPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void downloadImage(String imageUrl, String outputPath) {
        try {
            // 验证图片 URL 有效性
            if (!isValidImageUrl(imageUrl)) {
                System.err.println("无效的图片链接: " + imageUrl);
                return;
            }

            // 去掉查询参数
            String baseUrl = imageUrl.replaceAll("w_430","w_1024");
            HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl).openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Referer", "http://pichk.daydaycook.com/");

            try (InputStream in = connection.getInputStream()) {
                Files.copy(in, Paths.get(outputPath), StandardCopyOption.REPLACE_EXISTING);
                System.out.println("图片下载成功: " + outputPath);
            }
        } catch (Exception e) {
            System.err.println("图片下载失败: " + imageUrl + "，错误信息：" + e.getMessage());
        }
    }
    private static boolean isValidImageUrl(String imageUrl) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(5000);
            connection.connect();
            return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            return false;
        }
    }

    private static String getFileExtension(String url) {
        String extension = "";
        int lastIndex = url.lastIndexOf('.');
        if (lastIndex != -1) {
            extension = url.substring(lastIndex);
        }
        return extension.isEmpty() ? ".jpg" : extension;
    }
    // 内部类用于存储每行数据
    static class RowData {
        private final String content;
        private final String imageUrl;

        public RowData(String content, String imageUrl) {
            this.content = content;
            this.imageUrl = imageUrl;
        }

        public String getContent() {
            return content;
        }

        public String getImageUrl() {
            return imageUrl;
        }
    }
    private static String sanitizeFileName(String fileName) {
        // 替换非法字符为下划线
        return fileName.replaceAll("[\\\\/:*?\"<>|]", "").trim();
    }
}